﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DBSourceToolsLib;

namespace DBSourceTools
{
    public partial class DeployResultsForm : Form
    {
        private BatchRunner m_BatchRunner;
        string m_BatchFileName;
        string m_OutputFileName;
        private System.IO.StreamWriter m_outputStreamWriter;
        delegate void SetTextCallback(string text, int iErrorLevel);

        public DeployResultsForm(string strBatchFileName, string strOutputFileName)
        {
            InitializeComponent();
            m_BatchFileName = strBatchFileName;
            m_OutputFileName = strOutputFileName;
            m_BatchRunner = new BatchRunner(m_OutputFileName, m_BatchFileName, true);
            m_BatchRunner.ProgressEventPublisher += new EventHandler<ProgressEventArgs>(m_BatchRunner_ProgressEventPublisher);
            FileUtils.EnsureFileIsWriteable(m_OutputFileName);
            m_outputStreamWriter = new System.IO.StreamWriter(m_OutputFileName);

        }

        void m_BatchRunner_ProgressEventPublisher(object sender, ProgressEventArgs e)
        {
            try
            {
                if (m_outputStreamWriter != null)
                {
                    m_outputStreamWriter.WriteLine(e.Message);
                }
            }
            catch (System.ObjectDisposedException ex)
            {
                // the thread has closed the output file.
            }

            if (e.Percent.CompareTo("100") == 0)
            {
                this.SetText(e.Message + Environment.NewLine, 2);
                m_outputStreamWriter.Close();
                this.SetText(Environment.NewLine, 2);
                this.SetText(Environment.NewLine, 2);
                this.SetText("Results writting to : " + Environment.NewLine, 2);
                this.SetText(this.m_OutputFileName, 2);
                this.SetText(Environment.NewLine, 2);
                this.SetText(Environment.NewLine, 2);
                this.SetText("Completed", 2);
            }
            else
            {
                this.SetText(e.Message + Environment.NewLine, ( e.IsError ? 1 : 0));
            }
        }

        private void DeployResultsForm_Load(object sender, EventArgs e)
        {
            m_BatchRunner.RunUsingStreams();
        }

        private void SetText(string text, int iErrorLevel)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.m_richTextBoxResults.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text, iErrorLevel });
            }
            else
            {
                switch (iErrorLevel)
                {
                    case 0:
                        m_richTextBoxResults.SelectionColor = Color.White;
                        break;
                    case 1:
                        m_richTextBoxResults.SelectionColor = Color.Red;
                        break;
                    case 2:
                        m_richTextBoxResults.SelectionColor = Color.Green;
                        break;
                }

                this.m_richTextBoxResults.AppendText(text);
                this.m_richTextBoxResults.Update();
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (this.m_BatchRunner != null)
            {
                this.m_BatchRunner.Abort();
            }

        }

        private void DeployResultsForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.m_BatchRunner != null)
            {
                m_BatchRunner.ProgressEventPublisher -= m_BatchRunner_ProgressEventPublisher;
                this.m_BatchRunner.Abort();
            }

        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
        //    string strConstDBDir = "DB_BASE_DIR=";
        //    string strConstBinDir = "BASE_BIN_DIR=";
        //    string strDBBase = "";
        //    string strBinBase = "";

        //    using (System.IO.StreamReader oReader = new System.IO.StreamReader(m_BatchFileName))
        //    {
        //        string strLine = oReader.ReadLine();
        //        while (strLine != null)
        //        {
        //            bool bExecutable = true;
        //            if (strLine.Contains(strConstDBDir))
        //            {
        //                bExecutable = false;
        //                strDBBase = strLine.Substring(strLine.IndexOf(strConstDBDir) + strConstDBDir.Length );
        //            }
        //            if (strLine.Contains(strConstBinDir))
        //            {
        //                bExecutable = false;
        //                strBinBase = strLine.Substring(strLine.IndexOf(strConstBinDir) + strConstBinDir.Length);
        //            }
        //            if (strLine.StartsWith("rem"))
        //                bExecutable = false;
        //            if (bExecutable)
        //            {
        //                strLine = strLine.Replace("%DB_BASE_DIR%", strDBBase);
        //                strLine = strLine.Replace("%BASE_BIN_DIR%", strBinBase);
        //                string strCmd = "";// = strLine.Substring(0, strLine.IndexOf(" "));
        //                string strArgs = "";
        //                if (strLine.StartsWith("sqlcmd"))
        //                {
        //                    strCmd = "sqlcmd.exe";
        //                    strArgs = strLine.Substring(strLine.IndexOf(" "));
        //                }
        //                else
        //                {
        //                    // data loader
        //                    strCmd = strLine.Substring(0, strLine.IndexOf(".exe") + 5);
        //                    strArgs = strLine.Substring(strCmd.Length);
        //                }
                        

                        

        //                DosCmdRunner oRunner = new DosCmdRunner();
        //                oRunner.m_OutputFile = System.IO.Path.GetTempFileName();
        //                oRunner.m_Cmd = strCmd;
        //                oRunner.m_Args = strArgs;
        //                oRunner.Run();

        //                SetText(" Running " + strCmd + strArgs, 0);
        //                foreach (string strMessage in oRunner.m_StringList)
        //                {
        //                    SetText(Environment.NewLine + strMessage, 0);
        //                }
        //            }
        //            strLine = oReader.ReadLine();
        //        }
        //    }
        }

    }

    public class DosCmdRunner
    {
        public string m_OutputFile;
        public string m_Cmd;
        public string m_Args;
        public List<string> m_StringList = new List<string>();
        BatchRunner oRunner;

        internal void Run()
        {
            oRunner = new BatchRunner(m_OutputFile, m_Cmd, false);
            oRunner.ProgressEventPublisher += new EventHandler<ProgressEventArgs>(oRunner_ProgressEventPublisher);
            oRunner.AddArgument(m_Args);
            oRunner.RunUsingStreams();
            oRunner.Join();
        }

        void oRunner_ProgressEventPublisher(object sender, ProgressEventArgs e)
        {
            m_StringList.Add(e.Message);
        }
    }
}
